import router from './router'
import store from '@/store'

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  // 1.用户未登录，只允许进入 login
  // 2.已登录，不允许进入login
  // console.log(store.getters.token)
  if (store.getters.token) {
    // 已登录
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断用户资料是否存在
      if (!store.getters.hasUserInfo) {
        const { permission } = await store.dispatch('user/getUserInfo')
        // 添加动态路由表
        const filterRoutes = await store.dispatch('permission/filterRoutes', permission.menus)
        // 利用addRoutes 循环添加动态路由表
        filterRoutes.forEach(route => {
          router.addRoute(route)
        })
        // 添加完动态路由表之后，需要进行一次主动跳转
        return next(to.path)
      }
      next()
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
